<template>
  <div class="wrapper">
    <!-- 获取地址 -->
    <div class="shipment">
      <template v-if='address'>
        <view class="dt">收货人: </view>
        <view class="dd meta">
          <text class="name">{{address && address.userName}}</text>
          <text class="phone">{{address && address.telNumber}}</text>
        </view>
        <view class="dt">收货地址:</view>
        <view class="dd">{{detailAddress}}</view>
      </template>
      <button v-else @click='getAddress'>获取收获地址</button>
    </div>
    <!-- 购物车商品列表 -->
    <div class="carts">
      <div class="item">
        <view class="shopname">优购生活馆</view>
        <!-- 商品列表 -->
        <div class="goods" :key='item.goods_id' v-for='item in cart'>
          <!-- 商品图片 -->
          <image class="pic" :src="item.goods_icon"></image>
          <!-- 商品信息 -->
          <div class="meta">
            <div class="name">{{item.goods_name}}</div>
            <div class="price">
              <text>￥</text>{{item.goods_price}}<text>.00</text>
            </div>
            <!-- 加减 -->
            <div class="amount">
              <text class="reduce" @click='handleCalc(item.goods_id, -1)'>-</text>
              <input type="number" :value="item.goods_num" class="number">
              <text class="plus" @click='handleCalc(item.goods_id, 1)'>+</text>
            </div>
          </div>
          <!-- 选框 -->
          <div class="checkbox">
            <icon @click='toggleItem(item.goods_id)' type="success" size="20" :color="item.goods_flag?'#ea4451':'#eee'"></icon>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部菜单 -->
    <!-- 其它 -->
    <view class="extra">
      <label class="checkall">
        <!-- 这里三目运算符的条件不支持判断（uni-app存在的bug） -->
        <icon @click='toggleAll' type="success" :color="isAll?'#EA4451':'#eee'" size="20"></icon>
        全选
      </label>
      <view class="total">
        合计: <text>￥</text><label>{{calcTotal}}</label><text>.00</text>
      </view>
      <view class="pay" @click='toPay'>结算</view>
    </view>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        title: '购物车',
        address: null,
        cart: []
      }
    },
    onShow () {
      // 从缓存中获取最新的购物车数据
      this.cart = uni.getStorageSync('mycart') || []
    },
    computed: {
      calcTotal () {
        // 计算选中的商品总价
        let total = 0
        this.cart.forEach(item => {
          if (item.goods_flag) {
            // 单件 * 数量 再进行累加操作
            total += item.goods_price * item.goods_num
          }
        })
        return total
      },
      isAll () {
        // 判断全选按钮是否选中
        let flag = true
        // 判断每件商品的选中状态
        this.cart.forEach(item => {
          flag = flag && item.goods_flag
        })
        return flag
        // return this.cart.every(item => {
        //   return item.goods_flag
        // })
      },
      detailAddress () {
        const {provinceName, cityName, countyName, detailInfo} = this.address || {}
        // 拼接详细的地址
        return `${provinceName}${cityName}${countyName}${detailInfo}`
      }
    },
    methods: {
      getGoodsDetail () {
        // 生成订单商品详情参数
        // const list = []
        // this.cart.forEach(item => {
        //   list.push({
        //     goods_id: item.goods_id,
        //     goods_number: item.goods_num,
        //     goods_price: item.goods_price
        //   })
        // })
        // return list
        return this.cart.map(item => {
          if (item.goods_flag) {
            return {
              goods_id: item.goods_id,
              goods_number: item.goods_num,
              goods_price: item.goods_price
            }
          }
        })
      },
      async toPay () {
        // 进行结算
        /*
          1、判断是否选择了收获地址
          2、判断是否选中了商品
          3、判断是否登录了？如果没有登录，需要先进行登录，然后再跳回来继续支付
        */
        // 1、判断是否选择了收获地址
        if (!this.address) {
          uni.showToast({
            title: '请选择收货地址！'
          })
          return
        }
        // 2、判断是否选中了商品
        let flag = this.cart.some(item => {
          return item.goods_flag
        })
        if (!flag) {
          uni.showToast({
            title: '请选择商品!'
          })
          return
        }
        // 3、判断是否登录
        const token = uni.getStorageSync('mytoken')
        if (!token) {
          // 没有登录，跳转到登录页面进行登录
          uni.navigateTo({
            url: '/pages/auth/index'
          })
        }
        // 4、创建订单
        // 准备请求参数
        // 4-1、收货地址
        const address = this.detailAddress
        // 4-2、订单商品总价
        const total = this.calcTotal
        // 4-3、商品详情
        const goods = this.getGoodsDetail()
        const params = {
          order_price: total,
          consignee_addr: address,
          goods: goods
        }
        // 调用接口创建订单
        const data = await this.$request('my/orders/create', params, 'POST', {
          Authorization: token
        })
        // 如果生成订单就跳转到订单详情页面
        if (data.meta.status === 200) {
          uni.navigateTo({
            url: '/pages/order/index?order_number=' + data.message.order_number
          })
        } else {
          uni.showToast({
            title: data.meta.msg
          })
        }
      },
      toggleAll () {
        // 切换所有商品的选中和反选状态
        let flag = !this.isAll
        this.cart.forEach(item => {
          item.goods_flag = flag
          // item.goods_flag = !this.isAll
        })
        // 把变更后的数据同步到缓存
        uni.setStorageSync('mycart', this.cart)
      },
      toggleItem (id) {
        // 控制单个按钮的切换操作
        this.cart.some(item => {
          if (item.goods_id === id) {
            item.goods_flag = !item.goods_flag
            return true
          } else {
            return false
          }
        })
        // 把变更后的数据同步到缓存
        uni.setStorageSync('mycart', this.cart)
      },
      handleCalc (id, n) {
        // 控制商品数量的变更操作
        this.cart.some(item => {
          if (item.goods_id === id) {
            if (item.goods_num === 1 && n === -1) {
              uni.showToast({
                title: '至少需要有一件商品'
              })
            } else {
              item.goods_num += n
            }
            return true
          } else {
            return false
          }
        })
        // 把变更后的数据同步到缓存
        uni.setStorageSync('mycart', this.cart)
      },
      getAddress () {
        // 获取收货地址
        uni.chooseAddress({
          success: (res) => {
            this.address = res
          }
        })
      }
    }
  }
</script>
<style lang="less">
  .shipment {
    height: 100rpx;
    line-height: 2;
    padding: 30rpx 30rpx 40rpx 30rpx;
    font-size: 27rpx;
    color: #333;
    background-color: #fff;
    background-image: url(http://static.botue.com/ugo/images/cart_border%402x.png);
    background-size: contain;
    background-repeat: no-repeat;
    background-position: bottom;

    .dt {
      width: 140rpx;
      float: left;
      clear: both;
    }

    .dd {
      padding-left: 160rpx;
    }

    .meta {
      padding-right: 50rpx;
    }

    text.phone {
      float: right;
    }
  }

  .carts {
    background-color: #f4f4f4;
    padding-bottom: 110rpx;
    overflow: hidden;

    .shopname {
      padding: 30rpx;
      margin-top: 20rpx;
      font-size: 30rpx;
      color: #333;
      background-color: #fff;
      border-top: 1rpx solid #eee;
      border-bottom: 1rpx solid #eee;
    }

    .goods {
      display: flex;
      padding: 30rpx 20rpx 30rpx 0;
      margin-left: 100rpx;
      border-bottom: 1rpx solid #eee;
      background-color: #fff;
  
      position: relative;

      .checkbox {
        width: 101rpx;
        height: 100%;
        background-color: #fff;

        display: flex;
        justify-content: center;
        align-items: center;

        position: absolute;
        left: -100rpx;
        top: 0;
      }

      &:last-child {
        border-bottom: none;
      }

      .pic {
        width: 200rpx;
        height: 200rpx;
        margin-right: 30rpx;
      }

      .meta {
        flex: 1;
        font-size: 27rpx;
        color: #333;
        position: relative;
      }

      .name {
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .price {
        position: absolute;
        bottom: 0;

        color: #ea4451;
        font-size: 33rpx;

        text {
          font-size: 22rpx;
        }
      }

      .amount {
        position: absolute;
        bottom: 0;
        right: 20rpx;

        height: 48rpx;
        text-align: center;
        border: 1rpx solid #ddd;
        border-radius: 8rpx;

        display: flex;
        align-items: center;

        text {
          display: block;
          width: 60rpx;
          line-height: 48rpx;
          font-size: 36rpx;
          color: #ddd;
          text-align: center;
        }

        input {
          width: 60rpx;
          height: 48rpx;
          min-height: 48rpx;
          font-size: 27rpx;
          border-left: 1rpx solid #ddd;
          border-right: 1rpx solid #ddd;
        }
      }
    }
  }

  .extra {
    position: fixed;
    bottom: 0;
    /* #ifdef H5 */
    bottom: 50px;
    /* #endif */
    left: 0;
    z-index: 9;

    width: 750rpx;
    height: 96rpx;
    text-align: center;
    line-height: 96rpx;
    font-size: 36rpx;
    border-top: 1rpx solid #eee;
    background-color: #fff;
    color: #333;
    display: flex;

    .checkall {
      width: 140rpx;
      line-height: 1;
      margin-left: 25rpx;
      display: flex;
      align-items: center;

      icon {
        margin-right: 20rpx;
      }
    }

    .total {
      display: flex;
      justify-content: center;
      flex: 1;

      label, text {
        color: #ea4451;
        vertical-align: bottom;
        position: relative;
        bottom: -2rpx;
      }

      text {
        position: relative;
        bottom: -3rpx;
        font-size: 24rpx;

        &:first-child {
          margin-left: 10rpx;
        }
      }
    }

    .pay {
      width: 200rpx;
      background-color: #ea4451;
      color: #fff;
    }
  }
</style>